//
//  KATTextFieldWindow.m
//  KATFramework
//
//  Created by Yi Yu on 2018/1/19.
//  Copyright © 2018年 KatApp. All rights reserved.
//

#import "KATTextFieldWindow.h"


@interface KATTextFieldWindow ()


///标题
@property(nonatomic,retain) KATLabel *titleLabel;

///水平分割线
@property(nonatomic,retain) KATShape *splitH;

///垂直分割线
@property(nonatomic,retain) KATShape *splitV;

///确定按钮文本
@property(nonatomic,retain) KATLabelButton *leftButton;

///取消按钮文本
@property(nonatomic,retain) KATLabelButton *rightButton;

///输入框
@property(nonatomic,retain) UITextField *textField;

///键盘尺寸
@property(nonatomic,assign) CGSize keyboardSize;


@end



@implementation KATTextFieldWindow

//获取实例（标题、样式和事件）
+ (instancetype)windowWithTitle:(NSString *)title style:(KATTextStyle *)style leftButtonLabel:(NSString *)leftLabel leftButtonAction:(void (^)(NSString *text))leftAction rightButtonLabel:(NSString *)rightLabel rightButtonAction:(void (^)(NSString *text))rightAction;
{
    KATTextFieldWindow *window=[[[self alloc] init] autorelease];
    
    [window initData];
    
    window.isTapShadowToHide=NO;
    window.isTapContentToHide=NO;
    window.isBlurStyle=YES;
    window.showMode=KATPopWindowAnimationTypeBlurScale;
    window.hideMode=KATPopWindowAnimationTypeAlpha;
    
    [window initWindow];
    
    
    //样式
    window.contentWidth=sqrt(MIN(SCREEN_MIN,500.0))*15.0;
    window.contentPadding=sqrt(MIN(SCREEN_MIN,500.0))*0.8;
    window.buttonHeight=sqrt(MIN(SCREEN_MIN,500.0))*1.6;
    window.lineWidth=0.5;
    window.cornerRadius=10.0;
    window.lineColor=KCOLOR_LINE;
    window.location=window.placement;
    window.windowDelegate=window;
    
    
    //默认的样式
    if(!style)
    {
        style=[KATTextStyle textStyle];
        
        style.textFont=[UIFont boldSystemFontOfSize:window.contentPadding*1.16];
        style.textColor=KCOLOR_NIGHT;
        style.hasDateStyle=NO;
        style.textAlignment=NSTextAlignmentCenter;
        style.marginTop=1;
        style.marginLeft=1;
        style.marginRight=1;
        style.marginBottom=1;
    }
    
    window.titleLabel=[KATLabel labelWithFrame:CGRectZero andStyle:nil];
    
    [window.content addSubview:window.titleLabel];
    
    
    //输入框
    window.textField=[[[UITextField alloc] init] autorelease];
    window.textField.bounds=CGRectMake(0, 0, 0, window.buttonHeight);
    window.textField.font=[UIFont systemFontOfSize:window.buttonHeight*0.5];
    window.textField.textColor=KCOLOR_DARK;
    window.textField.textAlignment=NSTextAlignmentCenter;
    window.textField.layer.cornerRadius=4.0;
    window.textField.clipsToBounds=YES;
    window.textField.layer.borderColor=window.lineColor.CGColor;
    window.textField.layer.borderWidth=window.lineWidth;
    window.textField.backgroundColor=COLOR(COLOR_BACKGROUND-30);
    window.textField.clearButtonMode=UITextFieldViewModeWhileEditing;
    window.textField.delegate=window;
    [window.content addSubview:window.textField];
    
    
    //水平分割线
    window.splitH=[KATShape shape];
    [window.content.layer addSublayer:window.splitH];
    
    
    //垂直分割线
    window.splitV=[KATShape shape];
    [window.content.layer addSublayer:window.splitV];
    
    
    //点击事件
    window.leftAction=leftAction;
    window.rightAction=rightAction;
    
    __block typeof(KATTextFieldWindow *)weakWindow=window;
    
    //按钮
    window.leftButton=[KATLabelButton buttonWithFrame:RECT(0, 0, 0, 0) text:leftLabel font:nil color:KCOLOR_BLUE andAction:^
    {
        [weakWindow hide];
        
        if(weakWindow.leftAction)
        {
            weakWindow.leftAction(weakWindow.textField.text);
        }
    }];
    [window.content addSubview:window.leftButton];
    
    //按钮
    window.rightButton=[KATLabelButton buttonWithFrame:RECT(0, 0, 0, 0) text:rightLabel font:nil color:KCOLOR_BLUE andAction:^
    {
        [weakWindow hide];
        
        if(weakWindow.rightAction)
        {
            weakWindow.rightAction(weakWindow.textField.text);
        }
    }];
    [window.content addSubview:window.rightButton];
    
    
    window.title=title;
    window.titleStyle=style;
    
    window.filter=nil;
    window.countMax=128;
    
    [window updateWindow];
    
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:window selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //增加监听，当键盘出现后收出消息
    [[NSNotificationCenter defaultCenter] addObserver:window selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:window selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    return window;
}


- (void)setLocation:(CGPoint)location
{
    _location=location;
    self.placement=_location;
}


- (void)setTitle:(NSString *)title
{
    if(title!=_title)
    {
        [_title release];
        _title=[title copy];
        
        [self updateWindow];
    }
}


- (void)setTitleStyle:(KATTextStyle *)titleStyle
{
    if(titleStyle!=_titleStyle)
    {
        [_titleStyle release];
        _titleStyle=[titleStyle retain];
        
        [self updateWindow];
    }
}


- (void)setContentWidth:(float)contentWidth
{
    _contentWidth=contentWidth;
    
    [self updateWindow];
}


- (void)setContentPadding:(float)contentPadding
{
    _contentPadding=contentPadding;
    
    [self updateWindow];
}


- (void)setButtonHeight:(float)buttonHeight
{
    _buttonHeight=buttonHeight;
    
    [self updateWindow];
}


- (void)show
{
    [self updateWindow];
    
    [super show];
}


//更新窗口
- (void)updateWindow
{
    _titleLabel.frame=CGRectMake(_contentPadding, _contentPadding, _contentWidth-2*_contentPadding, 0);
    
    _titleLabel.text=_title;
    
    if(_title)
    {
        _titleLabel.style=_titleStyle;
        [_titleLabel adjustFrame];
        
        _textField.frame=CGRectMake(_contentPadding, _titleLabel.frame.origin.y+_titleLabel.frame.size.height+_contentPadding*0.5, _contentWidth-2*_contentPadding, _buttonHeight);
    }
    else
    {
        _textField.frame=CGRectMake(_contentPadding, _titleLabel.frame.origin.y+_titleLabel.frame.size.height, _contentWidth-2*_contentPadding, _buttonHeight);
    }
    
    
    _textField.layer.borderColor=_lineColor.CGColor;
    _textField.layer.borderWidth=_lineWidth;
    _textField.font=[UIFont systemFontOfSize:_buttonHeight*0.5];
    
    
    //水平分割线
    UIBezierPath *pathH=[[[UIBezierPath alloc] init] autorelease];
    [pathH moveToPoint:CGPointMake(0, 0)];
    [pathH addLineToPoint:CGPointMake(_contentWidth, 0)];
    
    _splitH.path=pathH.CGPath;
    _splitH.lineWidth=0.5;
    _splitH.strokeColor=_lineColor.CGColor;
    _splitH.bounds=CGRectMake(0, 0, _contentWidth, _lineWidth);
    _splitH.position=CGPointMake(_contentWidth*0.5, _textField.frame.origin.y+_textField.frame.size.height+_contentPadding);
    
    //垂直分割线
    UIBezierPath *pathV=[[[UIBezierPath alloc] init] autorelease];
    [pathV moveToPoint:CGPointMake(0, 0)];
    [pathV addLineToPoint:CGPointMake(0, _buttonHeight+_contentPadding)];
    
    _splitV.path=pathV.CGPath;
    _splitV.lineWidth=0.5;
    _splitV.strokeColor=_lineColor.CGColor;
    _splitV.bounds=CGRectMake(0, 0, _lineWidth, _buttonHeight+_contentPadding);
    _splitV.position=CGPointMake(_contentWidth*0.5, _textField.frame.origin.y+_textField.frame.size.height+_contentPadding+(_buttonHeight+_contentPadding)*0.5);
    
    
    //按钮
    _leftButton.frame=RECT(0, _textField.frame.origin.y+_textField.frame.size.height+_contentPadding, _contentWidth/2.0, _buttonHeight+_contentPadding);
    _leftButton.label.font=[UIFont boldSystemFontOfSize:_buttonHeight*0.618];
    
    _rightButton.frame=RECT(_contentWidth/2.0, _textField.frame.origin.y+_textField.frame.size.height+_contentPadding, _contentWidth/2.0, _buttonHeight+_contentPadding);
    _rightButton.label.font=[UIFont boldSystemFontOfSize:_buttonHeight*0.618];
    
    
    self.contentSize=CGSizeMake(_contentWidth, _textField.frame.origin.y+_textField.frame.size.height+_contentPadding+(_contentPadding+_buttonHeight));
    
    [self updateLocation];
}


//更新高度位置
- (void)updateLocation
{
    if(self.isShown)
    {
        if(_location.y+self.content.bounds.size.height*0.5+_contentPadding>SCREEN_HEIGHT-_keyboardSize.height)//键盘高度超标
        {
            self.content.layer.position=CGPointMake(_location.x, SCREEN_HEIGHT-_keyboardSize.height-self.content.bounds.size.height*0.5-_contentPadding);
        }
        else
        {
            self.placement=_location;
            self.content.layer.position=self.placement;
        }
    }
}


//背景点击
- (void)backgroundTap
{
    //关闭键盘
    [_textField resignFirstResponder];
}


//键盘将要显示
- (void)keyboardWillShow:(NSNotification *)notification
{
    _keyboardSize=[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    [self updateLocation];
}


//键盘完成显示
- (void)keyboardDidShow:(NSNotification *)notification
{
    _keyboardSize=[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    [self updateLocation];
}


//键盘消失
- (void)keyboardWillHide:(NSNotification *)notification
{
    _keyboardSize=CGSizeZero;
    
    [self updateLocation];
}


//调整窗口(方向改变系统通知处理)
- (void)resizeWindow
{
    [super resizeWindow];
    
    self.location=self.placement;
}


#pragma -mark 回调方法

//阴影点击
- (void)windowShadowTaped:(KATPopWindow *)popWindow
{
    [self backgroundTap];
}


//窗体点击
- (void)windowContentTaped:(KATPopWindow *)popWindow
{
    [self backgroundTap];
}


//窗口将要隐藏
- (void)windowWillHide:(KATPopWindow *)popWindow
{
    [self backgroundTap];
}


//窗口将要出现
- (void)windowWillShow:(KATPopWindow *)popWindow
{
    //清空输入框内容
    _textField.text=nil;
}


//窗口出现后
- (void)windowDidShow:(KATPopWindow *)popWindow
{
    //弹出键盘
    [_textField becomeFirstResponder];
}


//编辑内容字数限制
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField==_textField)
    {
        if(string.length==0)//退格键
        {
            return YES;
        }
        
        if([string hasSuffix:@"\n"])//回车键
        {
            if(textField.text.length>_countMax)//字数限定
            {
                textField.text=[textField.text substringToIndex:_countMax];
            }
            
            return NO;
        }
        
        if(_filter && _filter.length>0)//过滤器
        {
            for(NSString *exp in _filter)
            {
                if([KATExpressionUtil hasExpression:exp inString:string])
                {
                    return NO;
                }
            }
        }
        
        if(textField.text.length+string.length>_countMax)//字数限定
        {
            if(range.length>0)//输入法替换
            {
                if(textField.text.length-range.length+string.length<=_countMax)
                {
                    return YES;
                }
                else
                {
                    return NO;
                }
            }
            
            //拼音等输入法是否正在输入判断
            UITextRange *selectedRange=[textField markedTextRange];
            UITextPosition *position=[textField positionFromPosition:selectedRange.start offset:0];
            
            if(position)//正在输入
            {
                return YES;
            }
            else
            {
                if(textField.text.length>_countMax)
                {
                    textField.text=[textField.text substringToIndex:_countMax];
                }
                
                return NO;
            }
        }
        
        return YES;
    }
    
    return NO;
}


//编辑完成
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField.text.length>_countMax)//字数限定
    {
        textField.text=[textField.text substringToIndex:_countMax];
    }
}


//释放内存
- (void)dealloc
{
    //取消通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if(_leftAction)
    {
        Block_release(_leftAction);
    }
    
    if(_rightAction)
    {
        Block_release(_rightAction);
    }
    
    [_titleLabel release];
    [_title release];
    [_titleStyle release];
    [_lineColor release];
    [_splitH release];
    [_splitV release];
    [_leftButton release];
    [_rightButton release];
    [_textField release];
    [_filter release];
    
    [super dealloc];
}


@end
